<?php

$configFiles = new DirectoryIterator('/var/aegir/.tdc');
$aliasMap = mapAlias();

foreach($configFiles as $file) {
	if (!$file->isFile()) {
		continue;
	}
	
	$base = $file->getBaseName('.php');
	$dirty = $file->getBaseName();
	
	if ($base == $dirty) {
		continue;
	}
	
	processPlatform($base, $file->getPathname());
}

// wrap the command
function build_exec($cmd, &$output) {
	print $cmd . PHP_EOL;

	$output[] = '';
	$output[] = $cmd;
	
	$result = 0;
	$stdout = exec($cmd, $output, $result);
	
	return $result;
}

function build_assert($true, $msg) {
	if ($true === TRUE) {
		return;
	}
	throw new Exception($msg);
}

function processPlatform($base, $file) {
	// load the config
	@require($file);
	
	if (!is_array($config)) {
		return;
	}
		
	if ($config['project'] <> $base) {
		return;
	}
	
	if ($config['source'] == '') {
		return;
	}
	
	$info = simplexml_load_string(`svn info {$config['source']} --xml`);
	
	if (@$config['revision'] <> '') {
		$revinfo = simplexml_load_string(`svn info {$config['revision']} --xml`);
	} else {
		$revinfo = &$info;
	}
			
	$kind = (string)$info->entry->attributes()->kind;
	$rev  = (string)$revinfo->entry->commit->attributes()->revision;
	
	print_r(array($kind, $rev));
	
	global $aliasMap;
	
	$result = array();
	
	try {
		// check site alias
		if (!array_key_exists($config['project'], $aliasMap['platform'])) {
			// build platform, install site
			buildPlatform($config['project'], $config['source'], $rev, $kind, $result);
		} else {
			$map = $aliasMap['platform'][$config['project']];
			if (in_array($rev, $map)) {
				// nothing to release, the current one is already in the releases
				print "Not doing anything\n";
			} else {
				buildPlatform($config['project'], $config['source'], $rev, $kind, $result);
			}
		}
		
		if (!in_array($config['project'], $aliasMap['sites'])) {
			// needs to creat a new one
			buildSite($config['project'], $rev);
		} else {
			// needs to migrate the existing one
			migrateSite($config['project'], $rev);
		}
		
	} catch (Exception $e) {
		$result[] = "[$e]\n\n";
	}
	
	print implode(PHP_EOL, $result);
}

function buildPlatform($platform, $source, $rev, $kind) {
	if ($kind == 'file') {
		return buildPlatformFromMakefile($platform, $source, $rev);
	} else if ($kind == 'dir') {
		return buildPlatformFromSource($platform, $source, $rev);
	}
}

function buildPlatformFromSource($platform, $source, $rev, &$result) {

	$alias = "{$platform}_{$rev}";
	$destination = "/var/aegir/platforms/$alias";

	`cd /var/aegir`;

	$ret = build_exec("svn export $source $destination -q", $result);
	build_assert($ret == 0, 'Fout bij het downloaden van de source.');
	
	$cmd = "drush"
	  . " --root='$destination' provision-save"
	  . " '@platform_{$alias}'"
	  . " --context_type='platform' -v"
	  ;
	 
	// create the alias
	$ret = build_exec($cmd, $result);
	build_assert($ret == 0, 'Fout bij het maken van de platform alias.');
	
	$ret = build_exec("drush @platform_$alias provision-verify -v", $result);
	build_assert($ret == 0, 'Fout bij het uitvoeren van provision-verify.');
	
	$ret = build_exec("drush @hostmaster hosting-import @platform_$alias -v", $result);
	build_assert($ret == 0, 'Fout bij het uitvoeren van @hostmaster hosting-import.');
}

function buildPlatformFromMakefile($platform, $source, $rev) {
	$alias = "{$platform}_{$rev}";
	$destination = "/var/aegir/make/$alias.make";
	$result[] = build_exec("svn export $source $destination -q");
	
	if (!$result) {
		return FALSE;
	}
}

function mapAlias() {
	$configFiles = new DirectoryIterator('/var/aegir/.drush');
	
	$result = array(
		'platform' => array(),
		'server' => array(),
		'site' => array(),
	);
	
	foreach($configFiles as $file) {
		if ($file->isDir()) {
			continue;
		}
		
		$patterns = array(
			'platform' => '/platform_(.*)_(\d+)$/',
			'server' => '/server_(.*)$/',
			'site' => '/server_(.*)$/',
		);
		$name = $file->getBasename('.alias.drushrc.php');
		
		if (preg_match($patterns['platform'], $name, $matches)) {
			$result['platform'][$matches[1]][] = $matches[2];
		} else
		if (preg_match($patterns['server'], $name, $matches)) {
			$result['server'][] = $matches[1];
		} else
		if (preg_match($patterns['site'], $name, $matches)) {
			$result['site'][] = $matches[1];
		}
	}
		
	return $result;
}

function buildSite($project, $rev, &$result) {
	print "build site $project\n";
//	return;
	$ret = build_exec("drush provision-save '@$project'"
	  . " --context_type='site' --uri='$project.local'"
	  . " --platform='@{$project}_{$rev}'"
	  . " --server='@server_master'"
	  . " --db_server='@server_localhost'"
	  . " --profile='default'"
	  . " --client_name='admin'"
	  . " -v"
	  , $result);
	build_assert($ret == 0, 'Fout bij het maken van de site alias.');
	
	$ret = build_exec("drush '@$project' provision-install -v", $result);
	build_assert($ret == 0, 'Fout bij het installeren van de site.');
	
	$ret = build_exec("drush @hostmaster hosting-task '@platform_{$project}_{$rev}' verify -v", $result);
	build_assert($ret == 0, 'Fout bij het importeren van de site.');
	
	return TRUE;
}

function migrateSite($project, $rev, &$result) {
	print "migrate site $project to $rev\n";
//	return;
	$ret = build_exec("drush '@$project' provision-migrate '@platform_{$project}_{$rev}' -v", $result);
	build_assert($ret == 0, 'Fout bij het importeren van de site.');
}

print PHP_EOL;
